package com.core.service.email;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import java.util.Map;

@Service
@Slf4j
@RequiredArgsConstructor
public class NotificationService {

    private final JavaMailSender mailSender;

    /**
     * 处理预约成功通知的通用业务逻辑
     * @param payload 消息体
     */
    public void processReservationSuccessNotification(Map<String, Object> payload) {
        log.info("Processing reservation success notification: {}", payload);
        try {
            String toEmail = (String) payload.get("email");
            String classroomId= payload.get("classroomId").toString();
            String reservationDate = payload.get("reservationDate").toString();

            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setTo(toEmail);
            mailMessage.setFrom("2105135962@qq.com"); // 必须和 spring.mail.username 一样
            mailMessage.setSubject("【自习室预约系统】恭喜您，预约成功！");
            String text = String.format("尊敬的用户您好：\n\n您已成功预约 %s 的自习室【%s】。\n\n感谢您的使用！", reservationDate, classroomId);
            mailMessage.setText(text);

            mailSender.send(mailMessage);
            log.info("邮件发送成功至 {}", toEmail);
        } catch (Exception e) {
            log.error("发送预约成功邮件失败! Payload: {}", payload, e);
            // 抛出异常，让MQ的重试机制生效
            throw new RuntimeException("Email sending failed", e);
        }
    }
}